package xyz.wanwanwan.www.hrm._04_direct;

import com.rabbitmq.client.*;
import xyz.wanwanwan.www.hrm.util.ConnectionUtil;

import java.io.IOException;

public class Receiver {
    public static final String MQ_QUEUE_DIRECT_C1 = "mq_queue_direct_c1";
    //1.创建连接
    //2.创建通道
    //3.准备消息处理回调
    //4.监听队列，消费消息
    public static void main(String[] args) throws Exception {
        //1.创建连接
        Connection connection = ConnectionUtil.getConnection();
        //2.创建通道
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        //创建队列
        channel.queueDeclare(MQ_QUEUE_DIRECT_C1,true,false,false,null);
        //绑定交换机
        channel.queueBind(MQ_QUEUE_DIRECT_C1, Sender.MQ_EXCHANGE_DIRECT,"hh");
        channel.queueBind(MQ_QUEUE_DIRECT_C1, Sender.MQ_EXCHANGE_DIRECT,"xx");
        //3.准备消息处理回调
        //consumerTag 消费者的标签，在channel.basicConsume()去指定
        //envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志
        //(收到消息失败后是否需要重新发送)
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到direct信息了");
                System.out.println("consumerTag:" + consumerTag);
                System.out.println("交换机:" + envelope.getExchange());
                System.out.println("RoutingKey:" + envelope.getRoutingKey());
                System.out.println("DeliveryTag:" + envelope.getDeliveryTag());
                System.out.println("消息内容:" + new String(body));
                //手动签收消息
                //long deliveryTag, :交货的ID
                //boolean multiple：false,签收当前这一消息
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //4.监听队列，消费消息
        channel.basicConsume(MQ_QUEUE_DIRECT_C1,false,callback);
    }

}
